<template>
  <div ref="container"></div>
</template>

<script setup name="mk">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import Vditor from 'vditor';
import 'vditor/dist/index.css';

const props = defineProps({
  modelValue: String,
  height: {
    type: Number,
    default: 360
  },
  mode: {
    type: String,
    default: "wysiwyg" // sv/wysiwyg/ir
  }
});

const emit = defineEmits(['update:modelValue','change']);

const container = ref(null);
const vditor = ref(null);

const isEditorReady = ref(false)

onMounted(() => {
  vditor.value = new Vditor(container.value, {
    height: props.height,
    mode: props.mode,
    preview: {
      actions: [],
    },
    cache: {
      enable: false, // 禁用缓存
      id: 'vditor-' + Date.now() // 添加唯一ID
    },
    input: (value) => {
      if (value !== props.modelValue) {
        emit('update:modelValue', value);
        emit('change',value);
      }    },
    after: () => {
      isEditorReady.value = true // 标记编辑器已就绪
      vditor.value.setValue(props.modelValue || '');
    }
  });
  
});

onBeforeUnmount(() => {
  vditor.value?.destroy();
});
// 监听传进来的值,set到编辑器里
watch(
    () => props.modelValue,
    (newValue) => {
      if (isEditorReady.value && vditor.value?.getValue() !== newValue) {
        vditor.value?.setValue(newValue || '')
      }
    }
)
</script>
